<?php

/**
 * 
 * 
 *
 */
class Quad_Date_Calendar_Month {
 
	public $firstDay;
	public $lastDay;
	public $year;
	public $month;
	public $monthName;
	public $startOnDay;
	public $startOnDayNum = 0;
	protected static $_dayMap = array('sunday'=>0,'monday'=>1,'tuesday'=>2,'wednesday'=>3,'thursday'=>4,'friday'=>5,'saturday'=>6);
	
	public function __construct($year = null, $month = null, $startOnDay = 'sunday') {
		if ($year instanceof Quad_Date) {
			$this->firstDay = clone $year;
			$this->firstDay->setDay(1);
			$startOnDay = ($month ? $month : 'sunday');
		}		
		else {
			if ($year === null) {
				$year = date('Y');
			}
			if ($month === null) {
				$month = date('n');
			}
			$this->firstDay = Quad_Date::create("$year-$month-01");
		}
		
		$this->startOnDay = (is_int($startOnDay) ? array_search($startOnDay, self::$_dayMap) : strtolower($startOnDay));
		$this->startOnDayNum = (isset(self::$_dayMap[$this->startOnDay]) ? self::$_dayMap[$this->startOnDay] : 0);
		list ($year, $month) = explode(' ', $this->firstDay->format('Y n'));
		$this->year = $year;
		$this->month = $month;
		
		$this->lastDay = clone $this->firstDay;
		$this->lastDay->setToLastDayOfMonth();
		$this->monthName = $this->firstDay->format('F');
//Quad_Debug::dumpdie($this, (string) $this->firstDay, (string) $this->lastDay);		
	}
	
	public function getWeekdayNames($abbreviate = false) {
		$day = Quad_Date::create("next $this->startOnDay");
		$names = array();
		for ($i = 0; $i < 7; ++$i) {
			$names[] = $day->format($abbreviate ? 'D' : 'l');
			$day = $day->modify('+1 day');
		}
		return $names;
	}
	
	public function getWeeksArray() {
		$firstWeekday = (int) $this->firstDay->format('w');
		$daysInMonth = (int) $this->lastDay->format('d');
		$lastWeekday = (int) $this->lastDay->format('w');
		// initialize return array
		$weeksArr = array();
		$daysArr = array();
		// leading days
		$leadingDays = (($firstWeekday + (int) $this->startOnDayNum) % 7);
		$numDays = ceil(($daysInMonth + $leadingDays) / 7) * 7;
		$date = clone $this->firstDay;
		if ($leadingDays > 0) {
			$back = $leadingDays;
			$date->modify("-$back days");
		}
		$day = 0; 
		while ($day++ < $numDays) {
			if ($day <= $leadingDays) {
				$context = -1;
			}
			elseif ($day > $daysInMonth + $leadingDays) {
				$context = 1;
			}
			else {
				$context = 0;
			}
			$daysArr[] = new Quad_Date_Calendar_Day($this, clone $date, $context);
			if (($day % 7) == 0) {
				$weeksArr[] = $daysArr;
				$daysArr = array();
			}
			$date->modify('+1 day');	
		}
		return $weeksArr;
	}
    
}